package com.itheima.dbservice;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.mapper.QuestionMapper;
import com.itheima.pojo.Question;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

@DubboService
public class QuestionServiceApiImpl implements QuestionServiceApi {
    @Autowired
    private QuestionMapper questionMapper;

    @Override
    public Question getQuestionInfo(String userId) {
        LambdaQueryWrapper<Question> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Question::getUserId, userId);
        return questionMapper.selectOne(lqw);
    }

    //添加问题
    @Override
    public void addQuestion(Long uid, String content) {
        //构造查询条件
        LambdaQueryWrapper<Question> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Question::getUserId, uid);
        //判断是否存在
        Question question = questionMapper.selectOne(wrapper);
        if (ObjectUtil.isNull(question)) {
            Question question1 = new Question();
            question1.setUserId(uid);
            question1.setTxt(content);
            question1.setCreated(new Date(System.currentTimeMillis()));
            question1.setUpdated(new Date(System.currentTimeMillis()));
            //将问题插入此表中
            questionMapper.insert(question1);
            return;
        }
        //若存在就更新此表
        question.setTxt(content);
        question.setUpdated(new Date(System.currentTimeMillis()));
        questionMapper.update(question, wrapper);
    }

    //获取问题
    @Override
    public Question getQuestion(Long uid) {
        //构建条件查询
        LambdaQueryWrapper<Question> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Question::getUserId, uid);
        Question question = questionMapper.selectOne(wrapper);
        //判断问题是否存在
        if (ObjectUtil.isNull(question)) {
            Question question1 = new Question();
            question1.setTxt("请设置问题");
            question1.setId(uid);
            return question1;
        }
        //将查询结果返回
        return question;
    }
}
